package com.jd.jstable.utils;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.springframework.util.StringUtils;

/**
 * Created by chenyipu on 2018/4/10.
 */
public class ZooKeeperUtil {
    public static void createRecursively(ZkClient zkClient, String zkPath) {
        boolean ex = zkClient.exists(zkPath);
        if(!ex) {
            String[] paths = zkPath.split("/");
            StringBuilder sb = new StringBuilder();
            for (String path : paths) {
                if (!StringUtils.isEmpty(path)) {
                    sb.append('/');
                    sb.append(path);
                    if (!zkClient.exists(sb.toString())) {
                        zkClient.create(sb.toString(), null, CreateMode.PERSISTENT);
                    }
                }
            }
        }
    }
//    public static void createIfNotExists(ZkClient zkClient, String zkPath){
//        //检测是否存在路径
//        boolean ex = zkClient.exists(zkPath);
//        //如果存在则返回
//        if(!ex){
//            //不存在就逐步创建
//            String[] paths = zkPath.split("/");
//            int end  = 0 ;
//            String current;
//            while (end < paths.length){
//                current = makePath(paths, end);
//                ex = zkClient.exists(current);
//                if(!ex){
//                    zkClient.create(current, null, CreateMode.PERSISTENT);
//                }
//                end++;
//            }
//        }
//
//    }

    private static String makePath(String[] paths, int end) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ;i<= end; i++){
            sb.append('/');
            sb.append(paths[i]);
        }
        return sb.toString();
    }
}
